﻿using System;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using Model;


namespace PlatformClient
{
    public partial class UserForm : XtraForm
    {
        public UserForm()
        {
            InitializeComponent();                     
        }

        readonly DataTable _dtRole = MainForm.PositionService.RoleGetList("").Tables[0];
        string _strPwd = "";
        private void User_Load(object sender, EventArgs e)
        {           
            try
            {

                DataSet dsCompany = MainForm.PositionService.CompanyGetList("");
                if (dsCompany != null && dsCompany.Tables.Count > 0)
                {
                    foreach (DataRow row in dsCompany.Tables[0].Rows)
                    {
                        string id = row["Id"].ToString();
                        string name = row["CompanyName"].ToString();
                        ImageComboBoxItem item = new ImageComboBoxItem();
                        item.Description = name;
                        item.Value = id;
                        BeginInvoke(new MethodInvoker(() =>
                        {
                            comboBoxEdit_company.Properties.Items.Add(item);
                        }));
                    }
                }
                 
                BindGrid();
               
                for (int i = 0; i < _dtRole.Rows.Count; i++)
                { 
                  comboBoxEdit＿Rolename.Properties.Items.Add(_dtRole.Rows[i]["Rolename"].ToString());
                }
              
               
            } 
            catch (Exception ex)
            {
                Common.CommonRoutine.HandlingExceptions(ex, true);
                return;
            }
        }

        private void BindGrid()
        {
           try
           {
               DataSet ds = MainForm.PositionService.UserGetList("");
               gridControl1.DataSource = ds.Tables[0];
               DataRow row = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);
               if (row != null)
               {
                   textEdit_ID.Text = row["id"].ToString();
                   textEdit_UserName.Text = row["UserName"].ToString();
                   textEdit_Workid.Text = row["workid"].ToString();
                   memoEdit_Remark.Text = row["Remark"].ToString();
                   btn_modify.Enabled = true;
                   comboBoxEdit＿Rolename.Text = row["Rolename"].ToString();
                   _strPwd = row["Password"].ToString();
               }
           }
           catch (Exception ex)
           {
               Common.CommonRoutine.HandlingExceptions(ex, true);
               return;
           }
        }

        private void gridView1_RowClick_1(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            DataRow row = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);//
            if (row != null)
            { 
                textEdit_ID.Text = row["id"].ToString();
                textEdit_UserName.Text = row["UserName"].ToString();
                textEdit_Workid.Text = row["workid"].ToString();
                memoEdit_Remark.Text = row["Remark"].ToString();
                btn_modify.Enabled = true;
                comboBoxEdit＿Rolename.Text = row["Rolename"].ToString();
                _strPwd = row["Password"].ToString();

                comboBoxEdit_company.Text = row["CompanyId"].ToString();
            }
        } 

        private void simpleButton_add_Click(object sender, EventArgs e)
        {

            if (btn_add.Tag.ToString() =="新增")
            {
                textEdit_ID.Text="";
                textEdit_UserName.Text = "";
                textEdit_UserName.Enabled = true;
                textEdit_Workid.Text ="";
                textEdit_Workid.Enabled = true;
                memoEdit_Remark.Text ="";
                memoEdit_Remark.Enabled = true ;
                comboBoxEdit＿Rolename.Enabled = true;

                comboBoxEdit_company.Enabled = true;

                gridControl1.Enabled = false;
                btn_delete.Visible = false;
                btn_cancel.Visible = true;
                btn_modify.Visible = false;
                btn_cancel.Location = btn_modify.Location;
                btn_add.Image = Properties.Resources.UserForm_btnsave001;
                btn_add.Tag = "保存";
            }
            
            else 
            {
                if (!CheckInput()) return;
                string strUsername = textEdit_UserName.Text;
                const string strPwd = "666666";
                string strRoleid = _dtRole.Rows[comboBoxEdit＿Rolename.SelectedIndex]["id"].ToString();
                string strWorkid = textEdit_Workid.Text;
                string strRemark = memoEdit_Remark.Text;

                string strCompany =
                 comboBoxEdit_company.Properties.Items[
                 comboBoxEdit_company.SelectedIndex].Value.ToString();


                try 
                {
                    if(MainForm.PositionService.UserExist(strUsername))
                    {
                      XtraMessageBox.Show("该用户已存在！");
                        return;
                    }
                    UserInfo user = new UserInfo {
                        UserName =strUsername,
                        Password=strPwd,
                        Roleid=int.Parse(strRoleid),
                        workid =strWorkid , 
                        Remark = strRemark ,
                        CompanyId = int.Parse(strCompany)
                    };
                    if(MainForm.PositionService.UserAdd(user))
                    {
                       XtraMessageBox.Show("添加成功,用户名为【"+strUsername+"】,密码为【666666】！");
                        btn_add.Image = Properties.Resources.UserForm_btnadd001;
                        btn_add.Tag = "新增";
                        gridControl1.Enabled = true ;
                        btn_cancel.Visible = false;
                        btn_delete.Visible = true;
                        btn_modify.Visible = true;

                        comboBoxEdit_company.Enabled = false;

                        comboBoxEdit＿Rolename.Enabled = false;
                        textEdit_UserName.Enabled = false;
                        textEdit_Workid.Enabled = false;
                        memoEdit_Remark.Enabled = false;
                        DataSet ds = MainForm.PositionService.UserGetList("");
                        gridControl1.DataSource = ds.Tables[0];
                        gridView1.FocusedRowHandle = gridView1.RowCount - 1;
                        DataRow row = gridView1.GetDataRow(gridView1.DataRowCount - 1);
                        textEdit_ID.Text = row["id"].ToString();
                       
                    }
                    else
                    {
                        XtraMessageBox.Show("添加失败");
                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                    return;
                }
               
            }
            
        }

        private void simpleButton_cancel_Click(object sender, EventArgs e)
        {
            gridView1_RowClick_1(null,null);
            btn_add.Visible = true;
            btn_add.Image = Properties.Resources.UserForm_btnadd001;
            btn_add.Tag = "新增";
            btn_modify.Tag = "修改";
            btn_modify.Image = Properties.Resources.UserForm_btnmodify001;
            gridControl1.Enabled = true;
            btn_modify.Visible = true;
            btn_modify.Location = new Point(668,523);
            btn_delete.Visible = true;
            btn_cancel.Visible = false;
            textEdit_UserName.Enabled = false;
            textEdit_Workid.Enabled = false;
            memoEdit_Remark.Enabled = false;
            comboBoxEdit＿Rolename.Enabled = false;
            comboBoxEdit_company.Enabled = false;
        }

        private void simpleButton_delete_Click(object sender, EventArgs e)
        {
            DataRow row = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);
            string id;
            if (row == null)
            {
                XtraMessageBox.Show("请选择要删除的用户！");
                return;
            }
            id = row["id"].ToString();
            
            //if ( textEdit_ID.Text == string.Empty)
            //{
            //    XtraMessageBox.Show("请选择要删除的用户！");
            //    return;
            //}

            if (XtraMessageBox.Show("确认删除流水号为【" + id + "】的用户吗？", "警告", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    if (MainForm.PositionService.UserDelete(int.Parse(id)))
                    {
                        XtraMessageBox.Show("删除成功！");
                        //DataSet ds = MainForm.PositionService.UserGetList("");
                        //gridControl1.DataSource = ds.Tables[0];
                        //textEdit_Workid.Text = "";
                        //textEdit_UserName.Text = "";
                        //textEdit_ID.Text = "";
                        //memoEdit_Remark.Text = "";
                        //comboBoxEdit＿Rolename.SelectedIndex = -1;
                        BindGrid();
                    }
                    else
                    {
                        XtraMessageBox.Show("删除失败！");
                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                }

            }
        }

        private void simpleButton_modify_Click(object sender, EventArgs e)
        {
            DataRow row = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);
            string id;
            if (row == null)
            {
                XtraMessageBox.Show("请选择要删除的用户！");
                return;
            }
            id = row["id"].ToString();
            // if ( textEdit_ID.Text == string.Empty)
            //{
            //    XtraMessageBox.Show("请选择要修改的用户！");
            //    return;
            //}
             if (btn_modify.Tag.ToString() == "修改")
             {

                 gridControl1.Enabled = false;
                 btn_modify.Image = Properties.Resources.UserForm_btnsave001;
                 btn_modify.Tag = "保存";
                 btn_cancel.Location = btn_modify.Location;
                 btn_modify.Location = btn_add.Location;
                 btn_cancel.Visible = true;
                 btn_add.Visible = false;
                 btn_delete.Visible = false;
                 comboBoxEdit＿Rolename.Enabled = true;
                 textEdit_Workid.Enabled = true;
                 memoEdit_Remark.Enabled = true;
                 comboBoxEdit_company.Enabled = true;
             }
             else
             {
                 if (!CheckInput()) return;
                 string strid = id;
                 string strUsername = textEdit_UserName.Text;
                 string strRoleid = _dtRole.Rows[comboBoxEdit＿Rolename.SelectedIndex]["id"].ToString();
                 string strWorkid = textEdit_Workid.Text;
                 string strRemark = memoEdit_Remark.Text;

                 string strCompany = comboBoxEdit_company.Properties.Items[
                   comboBoxEdit_company.SelectedIndex].Value.ToString();


                 UserInfo user = new UserInfo {
                     id =int.Parse(strid),
                     UserName = strUsername,
                     Password = _strPwd ,
                     Roleid =int.Parse(strRoleid),
                     workid = strWorkid , 
                     Remark = strRemark,
                     CompanyId = int.Parse(strCompany)
                 };
               try
                  {
                     if (MainForm.PositionService.UserUpdate(user))
                     {
                         XtraMessageBox.Show("修改成功！");
                         gridControl1.Enabled = true;
                         btn_modify.Image = Properties.Resources.UserForm_btnmodify001;
                         btn_modify.Tag = "修改";
                         btn_modify.Location = btn_cancel.Location;
                         btn_add.Visible = true;
                         btn_delete.Visible = true;
                         btn_cancel.Visible = false;
                         comboBoxEdit＿Rolename.Enabled = false;
                         textEdit_UserName.Enabled = false;
                         textEdit_Workid.Enabled = false;
                         memoEdit_Remark.Enabled = false;


                         comboBoxEdit_company.Enabled = false;

                         //DataSet ds = MainForm.PositionService.UserGetList("");
                         //gridControl1.DataSource = ds.Tables[0];
                         //textEdit_ID.Text = "";
                         //textEdit_UserName.Text = "";
                         //textEdit_Workid.Text = "";
                         //comboBoxEdit＿Rolename.SelectedIndex = -1;
                         //memoEdit_Remark.Text = "";
                         BindGrid();
                     }
                     else
                     {
                         XtraMessageBox.Show("修改失败！");
                     }
                   }
              catch (Exception ex)
                  {
                      Common.CommonRoutine.HandlingExceptions(ex, true);
                      return;
                  }
             }
        }
        private bool CheckInput()
        {
            string strUsername = textEdit_UserName.Text.Trim();
            if (strUsername == string.Empty)
            {
                XtraMessageBox.Show("用户名不能为空！");
                textEdit_UserName.Focus();
                return false;

            }
            
            if (Encoding.GetEncoding("GBK").GetBytes(strUsername).Length > 20)
            {
                XtraMessageBox.Show("用户名输入长度太长");
                textEdit_UserName.Focus();
                return false;
            }
            if (comboBoxEdit＿Rolename.SelectedIndex <0)
            {
                XtraMessageBox.Show("请选择该用户的角色");
               // textEdit_Pwd.Focus();
                return false;
            
            }
            if(textEdit_Workid.Text.Length>45)
            {
                XtraMessageBox.Show("员工工号长度过长");
                textEdit_Workid.Focus();
                return false;
            }

            if (comboBoxEdit_company.SelectedIndex < 0)
            {
                XtraMessageBox.Show("请选择所属公司！");
                comboBoxEdit_company.Focus();
                return false;
            }
            return true;
        }
        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;
            Cursor = Cursors.Arrow;
        }

        private void Form_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }
    }
}